const quertstring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')
const { getSession, setSession } = require('./src/db/redis')

//session数据
// const SESSION_DATA = {}

//用于处理post data
const getPostData = (req) => {
    const promise = new Promise((resolve, reject) => {
        //判断是不是post方式
        if (req.method !== 'POST') {
            resolve({})
            return
        }
        //判断返回类型
        if (req.headers['content-type'] !== 'application/json') {
            resolve({})
            return
        }
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(JSON.parse(postData))
        })

    })
    return promise
}
//新建cookie的expries
const getCookieExpires = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    console.log(d.toGMTString());
    return d.toGMTString()

}

const serverHandle = (req, res) => {
    //设置返回格式JSON
    res.setHeader('content-type', 'application/json;charset=utf-8')

    //获取path
    const url = req.url
    req.path = url.split('?')[0]

    //获取query
    req.query = quertstring.parse(url.split('?')[1])

    //解析cookie
    req.cookie = {}
    const cookieStr = req.headers.cookie || ''
    cookieStr.split(';').forEach(ele => {
        if (!ele) {
            return
        }
        const arr = ele.split('=')
        const key = arr[0].trim()
        const val = arr[1].trim()
        req.cookie[key] = val
    })

    //解析 session
    // let needSetCookie = false
    // let userId = req.cookie.userid
    // if (userId) {
    //     if (!SESSION_DATA[userId]) {
    //         SESSION_DATA[userId] = {}
    //     }
    // } else {
    //     needSetCookie = true
    //     userId = `${Date.now()}_${Math.random()}`
    //     SESSION_DATA[userId] = {}

    // }
    // req.session = SESSION_DATA[userId]

    //引用redis存储session
    let needSetCookie = false
    let userId = req.cookie.userid
    if (!userId) {
        needSetCookie = true
        userId = `${Date.now()}_${Math.random()}`
        //初始化redis 里的session值
        setSession(userId, {})
    }
    //从redis获取session
    req.sessionId = userId
    getSession(req.sessionId).then(sessionData => {
        if (sessionData == null) {
            //初始化redis 里的session值
            setSession(req.sessionId, {})
            // 设置session
            req.session = {}
        } else {
            req.session = sessionData
        }
        console.log('req.session', req.session);

        //处理post data
        return getPostData(req)
    })
        .then(postData => {
            req.body = postData

            //处理blog路由
            const blogResult = handleBlogRouter(req, res)
            if (blogResult) {
                blogResult.then(blogData => {
                    if (needSetCookie) {
                        res.setHeader('Set-Cookie', `userid ='${userId}';path=/;httpOnly;expires = '${getCookieExpires()}' `)
                    }
                    res.end(
                        JSON.stringify(blogData)
                    )
                })
                return
            }
            //处理user路由
            const userResult = handleUserRouter(req, res)
            if (userResult) {
                userResult.then(userData => {
                    if (needSetCookie) {
                        res.setHeader('Set-Cookie', `userid ='${userId}';path=/;httpOnly;expires = '${getCookieExpires()}' `)
                    }
                    res.end(
                        JSON.stringify(userData)
                    )
                })
                return
            }

            //未命中路由 返回404
            res.writeHead(404, { 'Conten-type': 'test/plain' })
            res.write("404 Not Found \n")
            res.end()

        })




}
module.exports = serverHandle